package com.zhieasy.common.dao.impl;

import com.zhieasy.common.dao.UserDao;
import com.zhieasy.common.util.JDBCUtil;
import com.zhieasy.xpuapi.entity.StudentPojo;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * @author Xuniverse
 * 通过Dao类操作数据库
 */
public class UserDaoImpl implements UserDao {

    private JdbcTemplate template = new JdbcTemplate(JDBCUtil.getDataSource()); //传递Druid数据源

    /**
     * 添加学生信息
     * @param studentPojo
     * @return
     */
    @Override
    public int addUser(StudentPojo studentPojo) {

        //添加学生信息
        String sql = "insert into stu values(null,?,?,?,?,?)";
        int res = template.update(sql,
                studentPojo.getStudentId(),
                studentPojo.getStudentName(),
                studentPojo.getCollege(),
                studentPojo.getMajor(),
                studentPojo.getGrade()
        );

        //重新添加主键自动增长
//        template.execute("ALTER TABLE stu DROP stu_number");
//        template.execute("ALTER TABLE stu ADD stu_number int NOT NULL FIRST");
//        template.execute("ALTER TABLE stu MODIFY COLUMN stu_number int NOT NULL AUTO_INCREMENT,ADD PRIMARY KEY(stu_number)");

        return res;
    }

    /**
     * 通过学号查找学生
     * @param studentId
     * @return
     */
    @Override
    public String findUser(String studentId) {
        String sql = "select studentName from stu where studentId = ?";
        String studentName = null;
        try {
            studentName = template.queryForObject(sql, String.class, studentId);
        } catch (DataAccessException e) {}
        return studentName;
    }
}
